<template>
    <view style="height:100%">
        <div v-if="mobileStyle ==3" style="flex: 1;overflow: hidden">
            <FormBoListStylize3 :total="total" @skip="skip" @change="change" @next="nextPage" @previous="previous"
                                :idField="idField" :multiSelect="multiSelect" :pageNo="pageNo" :totalCount="totalCount"
                                :isDialog="isDialog" :columns="columnsList" :dataList="dataList"
                                :buttonList="buttonList"
                                :mobileStyleList="mobileStyleList" :formBoListData="formBoListData"
                                :mobileConf="mobileConf"></FormBoListStylize3>
        </div>
        <div v-else class="DataList-common">
            <div class="DataList-list-pattern" v-for="(item,index) in dataList" :key="index">
                <div class="DataList-list-common-radio" v-if="isDialog=='YES' || formBoListData.hasSelect">
                    <radio style="transform:scale(0.7)" v-if="!multiSelect" @click="change(item)"
                           :checked='checked(item)'/>
                    <checkbox style="transform:scale(0.7)" v-else @click="change(item)" :checked='checked(item)'/>
                </div>
                <div class="DataList-list-pattern-ri">
                    <div class="DataList-list">
                        <form-bo-list-stylize
                            :stylize="stylize"
                            :columns="columnsList"
                            :item="item"
                            :index="index"
                            :buttonList="buttonList"
                            @next="nextPage"
                        >
                        </form-bo-list-stylize>
                    </div>
                </div>
            </div>
        </div>
        <div class="DataList-more" v-if="loading">
            <uv-loading-icon mode="spinner" :text="i18n('Loading','正在加载....')"></uv-loading-icon>
        </div>
        <RxEmptyList v-if="dataList.length==0 &&!initLoading"></RxEmptyList>
        <div v-else-if="!initLoading && mobileStyle!='3'">
           <span v-if="!parentField">
           <div v-if="pageNo < total" @click="nextPage" class="DataList-more">{{
                   $ti18('rxList.clickLoadMore', '点击加载更多')
               }}</div>
           <div v-else class="DataList-more"><span>{{ $ti18('rxList.noMore', '没有更多') }}</span></div>
        </span>
        </div>
        <RxLoading v-if="initLoading"></RxLoading>
    </view>
</template>

<script>
import FormBoListStylize from "./FormBoListStylize"
import FormBoListStylize3 from "../stylize/FormBoListStylize3";
import rxAjax from '@/assets/ajax.js';
import util from './util.js'
import RxLoading from '@/components/RxLoading'
import RxEmptyList from "@/components/RxEmptyList.vue"

export default {
    name: "FormBoListTable",
    mixins: [util],
    inject: {
        /**
         * 注入对话框实例数据.
         */
        dialogVm: {
            default: () => {
            }
        }
    },
    components: {
        FormBoListStylize,
        FormBoListStylize3,
        RxLoading,
        RxEmptyList
    },
    props: {
        isDialog: {
            type: String
        },
        stylize: {
            type: Number,
            default: 1//列表风格一共3种
        },
        isLazy: {
            type: Boolean,
            default: false
        },
        showPage: {
            type: Boolean,
            default: true//是否分页
        },
        defaultPageSize: {
            type: Number,
            default: 10//一页多少条
        },
        loadDataOnstart: {
            type: Boolean,
            default: true
        },
        queryParam: {
            type: Object,
            default() {
                return {}//查询参数
            }
        },
        defaultShowMobileColumns: {
            type: Array,
            default: () => []
        },
        showMobileColumns: {
            type: Array,
            default: () => []
        },
        hasMobileAllColumns: {
            type: String
        },
        hasMobileAllRight: {
            type: String
        },
        mobileBtnRight: {
            type: Array,
            default() {
                return []
            }
        },
        columns: {
            type: Array,
            default() {
                return []
            }
        },
        idField: {
            type: String,
            default: 'idx_'
        },
        textField: {
            type: String,
            default: 'name'
        },
        dataField: {
            type: String,
            default: ''
        },
        parentField: {
            type: String,
            default: 'parentId'
        },
        ajaxType: {
            type: String,
            default: 'post'
        },
        contentType: {
            type: String,
            default: 'json'
        },
        url: {
            type: String
        },
        multiSelect: {
            type: Boolean,
            default: true
        },
        mobileButton: {
            type: Array,
            default() {
                return []
            }
        },
        mobileConf: {
            type: Object,
            default() {
                return {}//查询参数
            }
        },
        formBoListData: {
            type: Object
        }
    },
    data() {
        return {
            isTable: true,
            show: false,
            pageSize: 10,
            pageNo: 1,
            //总的页数
            total: 0,
            //总的记录数
            totalCount: 0, //共数据条
            loading: false,
            buttonList: [],
            dataList: [],
            initList: [],
            checkedId: [], //选中列表的id
            /**
             * 选中的数据.
             */
            checkeds: [],
            column: [], //导航栏
            actionShow: false,
            async: this.isLazy,
            rowButtons: [], //行内更多按钮
            curRow: {},
            mobileStyle: '',
            mobileStyleList: {},//列表风格的属性
            columnsList: [],
            initLoading: true,//初始化
        }
    },
    created() {
        this.parseQueryParams()
        this.init();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formSolutionLang", key);
        },
        parseQueryParams() {
            this.mobileStyle = this.mobileConf.mobileStyle;
            this.mobileStyleList = this.mobileConf.mobileStyleList;
            var ary = this.mobileConf.mobileSearch.filter(item => {
                return item.type == 'query';
            });
            ary.forEach(item => {
                let field = item.fieldName;
                if (item.fc == 'month' || item.fc == 'rangepicker') {
                    field = 'queryField_' + field;
                } else if (item.autoFilter == 'YES') {
                    field = item.fc == 'datepicker' ? 'Q_' + (item.tablePre ? item.tablePre + '.' : '') + field + '_D_' + item.fieldOp : 'Q_' + (item.tablePre ? item.tablePre + '.' : '') + field + '_S_' + item.fieldOp;
                }
                this.getDefaultQueryValue(this.queryParam, field, item)
            })
        },
        init() {
            if (this.defaultPageSize) {
                this.pageSize = this.defaultPageSize;
            }
            if (this.loadDataOnstart) {
                this.loadData(true, false);
            }
            let ary = this.mobileButton.filter(item => {
                return item.btnType == 'row';
            });
            if (this.hasMobileAllRight !== undefined && (!this.hasMobileAllRight || this.hasMobileAllRight != "YES")) {
                //按钮过滤
                ary = ary.filter(item => {
                    if (this.mobileBtnRight && this.mobileBtnRight.length > 0) {
                        return this.mobileBtnRight.includes(item.btnName);
                    }
                })
                //字段过滤
                this.showMobileColumns.filter(res => {
                    this.columns.filter(obj => {
                        if (obj.field == res) {
                            this.columnsList.push(obj)
                        }
                    })
                })
            } else {
                this.columnsList = this.columns
            }
            if (ary.length == 0) {
                return;
            }
            this.buttonList = ary;
        },
        loadData(initPage, merge, params) {
            if (initPage) {
                this.pageNo = 1;
            } else {
                this.pageNo = this.pageNo;
            }
            let self = this;
            this.load(this.url, params, function (res) {
                self.initLoading = false
                self.parseForm(res, merge);
                //处理初始化数据。
                self.handInitData();
            })
        },
        load(url, params, callback) {
            if (url) {
                let _parameter = {
                    pageNo: this.pageNo,
                    pageSize: this.pageSize,
                    sortOrder: "asc"
                };
                if (this.queryParam) { //判断用url获取数据时，外部是否传入参数；
                    if (typeof this.queryParam == "object") {
                        _parameter.params = this.queryParam;
                    }
                }
                if (params) {
                    if (typeof params == "object") {
                        _parameter.params = Object.assign(_parameter.params, params);
                    }
                }
                if (this.ajaxType == "get") {
                    rxAjax.get(this.url, _parameter).then(res => {
                        if (callback) {
                            callback(res);
                        }
                    });
                } else if (this.ajaxType == "post") {
                    if (this.contentType == "json") {
                        rxAjax.postJson(this.url, _parameter).then(res => {
                            if (callback) {
                                callback(res);
                            }
                        })
                    } else if (this.contentType == "form") {
                        rxAjax.postForm(this.url, _parameter).then(res => {
                            if (callback) {
                                callback(res);
                            }
                        })
                    }
                }
            }
        },
        parseForm(res, merge) {
            this.loading = false;
            let result = res.result;
            //分页数量
            this.total = this.showPage ? result.totalPage : 1;
            this.totalCount = result.totalCount;
            let data = this.parseRes(res);
            data = this.listToTree(data, this.idField, this.parentField);
            this.dataList = merge ? [...this.dataList, ...data] : data;
            let ary = this.deepClone(data);
            this.initList = merge ? [...this.initList, ...ary] : ary;
        },
        getDefaultQueryValue(querys, field, config) {
            if (!config || !config.defaultValConf) {
                return;
            }
            let defaultValConf = JSON.parse(config.defaultValConf);
            if (!defaultValConf.defaultVal) {
                return;
            }
            if (defaultValConf.type == 'textbox') {
                querys[field] = defaultValConf.defaultVal;
            } else if (defaultValConf.type == 'datepicker') {
                let defaultValue = defaultValConf.defaultVal;
                defaultValue = this.getDateQueryValue(defaultValConf, defaultValue);
                querys[field] = defaultValue;
                let queryField = config.fieldName;
                if (config.autoFilter == 'YES') {
                    queryField = "Q_" + (config.tablePre ? config.tablePre + "." : "") + config.fieldName + "_D_" + config.fieldOp;
                }
                querys[queryField] = defaultValue;
            } else if (defaultValConf.type == 'rangepicker') {
                let defaultValue = defaultValConf.defaultVal;
                let valueAry = [];
                for (let i = 0; i < defaultValue.length; i++) {
                    valueAry[i] = this.getDateQueryValue(defaultValConf, defaultValue[i]);
                }
                querys[field] = valueAry.join(",");
                let queryField = (config.tablePre ? config.tablePre + "." : "") + config.fieldName;
                if (config.autoFilter == 'YES') {
                    querys["Q_" + queryField + "_D_GE"] = valueAry[0];
                    querys["Q_" + queryField + "_D_LE"] = valueAry[1];
                } else {
                    querys[queryField + "_START"] = valueAry[0];
                    querys[queryField + "_END"] = valueAry[1];
                }
            } else if (defaultValConf.type == 'month') {
                let defaultValue = defaultValConf.defaultVal;
                let valueAry = this.getMonthQueryValue(defaultValConf, defaultValue);
                querys[field] = valueAry[0];
                let queryField = (config.tablePre ? config.tablePre + "." : "") + config.fieldName;
                if (config.autoFilter == 'YES') {
                    querys["Q_" + queryField + "_D_GE"] = valueAry[1];
                    querys["Q_" + queryField + "_D_LE"] = valueAry[2];
                } else {
                    querys[queryField + "_START"] = valueAry[1];
                    querys[queryField + "_END"] = valueAry[2];
                }
            } else if (defaultValConf.type == 'select') {
                querys[field] = defaultValConf.defaultVal;
            } else if (defaultValConf.type == 'treeselect') {
                querys[field] = defaultValConf.defaultVal;
            } else if (defaultValConf.type == 'dialog') {
                let json = JSON.parse(defaultValConf.defaultVal)
                var nameKey = field.replace(config.fieldName, config.fieldName + "_display");
                querys[field] = json.value;
                querys[nameKey] = json.text;
            }
        },
        getDateQueryValue(defaultValConf, defaultValue) {
            if (defaultValue.indexOf("today") != -1) {
                defaultValue = defaultValue.replace("today", "");
                let num = parseInt(defaultValue.substring(0, defaultValue.length - 1));
                let unit = defaultValue.substring(defaultValue.length - 1);
                let format = defaultValConf.format;
                if (!format) {
                    format = 'YYYY-MM-DD';
                }
                if (format == 'YYYY-MM-DD HH:mm:ss') {
                    format = 'YYYY-MM-DDTHH:mm:ss';
                }
                defaultValue = moment().add(num, unit).format(format);
            }
            return defaultValue;
        },
        getMonthQueryValue(defaultValConf, defaultValue) {
            if (defaultValue.indexOf("month") != -1) {
                defaultValue = defaultValue.replace("month", "");
                let num = parseInt(defaultValue.substring(0, defaultValue.length - 1));
                let unit = defaultValue.substring(defaultValue.length - 1);
                let format = defaultValConf.format;
                if (!format) {
                    format = 'YYYY-MM';
                }
                let date = moment().add(num, unit);
                defaultValue = date.format(format);
                return [defaultValue, date.format("YYYY-MM") + "-01", date.format("YYYY-MM") + "-" + date.daysInMonth()];
            }
            let date = moment(defaultValue, "YYYY-MM");
            return [defaultValue, defaultValue + "-01", defaultValue + "-" + date.daysInMonth()];
        },
        nextPage(type) {
            this.loading = true;
            this.pageNo++;
            if (type == 'list') {
                this.dataList = [];
            }
            this.loadData(false, true);
        },
        previous() {
            this.loading = true;
            this.pageNo--;
            this.dataList = [];
            this.loadData(false, true);
        },
        skip(index) {
            this.loading = true;
            this.pageNo = index;
            this.dataList = [];
            this.loadData(false, true);
        },
        // 判断选中是否选中
        checked(item) {
            if (this.checkedId.includes(item[this.idField])) {
                return true
            } else {
                return false
            }
        },
        change(item) {
            if (!this.multiSelect) {
                this.checkedId = [];
                this.checkeds = [];
                this.checkedId.push(item[this.idField]);
                this.checkeds.push(item);
            } else {
                if (this.checkedId.includes(item[this.idField])) {
                    this.checkedId = this.checkedId.filter(res => {
                        if (res != item[this.idField]) {
                            return res
                        }
                    })
                    this.checkeds = this.checkeds.filter(res => {
                        if (res[this.idField] != item[this.idField]) {
                            return res
                        }
                    })

                } else {
                    this.checkedId.push(item[this.idField]);
                    this.checkeds.push(item);
                }
            }
        },
        getData() {
            return this.checkeds;
        },
        /**
         * 处理初始化数据.
         */
        handInitData() {
            let initData = this.dialogVm && this.dialogVm.initData;
            let selected = initData && initData.keyField && initData.selected;
            if (!selected || selected.length == 0) {
                return;
            }
            let keyField = initData.keyField;
            let tmpAry = [];
            for (let i = 0; i < selected.length; i++) {
                let val = selected[i];
                let ary = this.dataList.filter(item => {
                    return item[keyField] == val;
                });
                if (ary.length > 0) {
                    tmpAry.push(...ary);
                }
            }
            this.checkeds = tmpAry;
            this.checkedId = tmpAry.map(res => {
                return res[this.idField]
            })
        }
    },
    watch:{
        checkeds:{
            handler: function(type) {
                this.$emit('initRows',type)
            },
            deep:true

        }
    }
}
</script>

<style scoped>
.DataList-list-pattern {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 1rem;
}

.DataList-list-pattern-ri {
    flex: 1;
    overflow: hidden;
}

.DataList-list {
    background-color: #ffffff;
    box-shadow: 0px 2px 4px 0px rgba(50, 71, 119, 0.06);
    border-radius: 5px;
}

.DataList-common {
    flex: 1;
}

.DataList-empty {
    margin-top: 5rem;
    text-align: center;
    color: #d5ddea;
}

.DataList-empty i {
    color: #d5ddea;
    font-size: 3.5rem;
    line-height: 1rem;
}

.DataList-more {
    margin-top: 0.5rem;
    text-align: center;
}
.DataList-more span{
    color: #999999;
}
</style>

